package com.mobisys.live.controller;

import com.alibaba.fastjson.JSON;
import com.mobisys.live.bean.im_group.ImportUserIdBean;
import com.mobisys.live.bean.user.UpdatePassword;
import com.mobisys.live.bean.xidian_user.OnUndergraduate;
import com.mobisys.live.bean.xidian_user.Onteacher;
import com.mobisys.live.bean.xidian_user.Yjs;
import com.mobisys.live.dao.mapper.DictPackageMapper;
import com.mobisys.live.dao.mapper.PackageUsageMapper;
import com.mobisys.live.dao.model.DictPackage;
import com.mobisys.live.dao.model.PackageUsage;
import com.mobisys.live.im.TimRestApi;
import com.mobisys.live.response.tim.TimResponse;
import com.mobisys.live.response.user.UserInfoResponseBody;
import org.apache.ibatis.jdbc.Null;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.mobisys.live.bean.user.UserInfo;
import com.mobisys.live.dao.mapper.UserMapper;
import com.mobisys.live.dao.model.User;
import com.mobisys.live.response.Response;

import org.jasig.cas.client.authentication.AttributePrincipal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import java.security.Principal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import static com.mobisys.live.config.ResponseCode.*;

/**
 * @author gwg
 * @date 2018/1/23 20:34
 * 用户登陆、注册等相关操作接口
 */
@RestController
//@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {
    private Logger logger = LogManager.getLogger(UserController.class.getName());


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DictPackageMapper dictPackageMapper;

    @Autowired
    private PackageUsageMapper packageUsageMapper;

    private RestTemplate restTemplate = new RestTemplate();
    private ResponseEntity<String> responseEntity ;
    /**
     * 用户登陆
     *
     * @param userInfo
     * @param httpServletRequest
     */
    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public Response login(@RequestBody UserInfo userInfo, HttpServletRequest httpServletRequest) {
        logger.debug(userInfo);

        Response response = new Response<UserInfoResponseBody>();
        logger.debug(userInfo);

        //获取用户
        User user = userMapper.selectByUserName(userInfo.getUserName());
        logger.debug("database:" + user);

        if (user == null) {
            response.setRetureValue(USER_DOES_NOT_EXSIT);
            response.setRetureMsg(MSG_USER_DOES_NOT_EXSIT);
            return response;
        }
        System.out.println(user.getPassword() + " " + userInfo.getPassword());
        if (!user.getPassword().equals(userInfo.getPassword())) {
            response.setRetureValue(USERNAME_OR_PASSWORD_INCORRECT);
            response.setRetureMsg(MSG_USERNAME_OR_PASSWORD_INCORRECT);
            return response;
        }
        UserInfoResponseBody userInfoResponseBody = new UserInfoResponseBody();
        userInfoResponseBody.setUserId(user.getId());
        userInfoResponseBody.setUserName(user.getUsername());
        response.setRetureValue(SUCCESS);
        response.setRetureMsg(MSG_SUCCESS);
        response.setRetureData(userInfoResponseBody);
        return response;
    }

    /**
     * 用户注册
     *
     * @param userInfo
     * @param httpServletRequest
     */
    @RequestMapping(value = "/user/register", method = RequestMethod.POST)
    public Response register(@RequestBody UserInfo userInfo, HttpServletRequest httpServletRequest) {
        Response response = new Response<UserInfoResponseBody>();

        User user = userMapper.selectByUserName(userInfo.getUserName());
        if(user != null){
            response.setRetureValue(USER_HAS_EXSIT);
            response.setRetureMsg(MSG_USER_HAS_EXSIT);
            return response;
        }
        user = new User();
        user.setUsername(userInfo.getUserName());
        user.setPassword(userInfo.getPassword());

        //将帐号导入腾讯云即时通信
        ImportUserIdBean importUserIdBean=new ImportUserIdBean();
        importUserIdBean.setIdentifier(user.getId());
        TimResponse timResponse=TimRestApi.importToIM(importUserIdBean);
        if(timResponse.getErrorCode()!=0){
            //如果帐号导入失败则返回
            response.setRetureValue(IM_SDK_IMPORT_USER_ERROR);
            response.setRetureMsg(MSG_IM_SDK_IMPORT_USER_ERROR);
            return response;
        }

        if (user == null) {
            response.setRetureValue(USER_DOES_NOT_EXSIT);
            response.setRetureMsg(MSG_USER_DOES_NOT_EXSIT);
            return response;
        }
        if (userMapper.insertSelective(user) > 0) {
            //设置新用户的资源余量
            PackageUsage packageUsage = new PackageUsage();
            DictPackage dictPackage = dictPackageMapper.selectByPrimaryKey("0");
            if(packageUsage == null || dictPackage == null){
                response.setRetureValue(GET_RESOURCE_ERROR);
                response.setRetureMsg(MSG_GET_RESOURCE_ERROR);
                return response;
            }
            packageUsage.setDictPackageId("0");
            packageUsage.setRemainChannelNum(dictPackage.getChannelNum());
            packageUsage.setRemainLiveCapacity(dictPackage.getLiveCapacity());
            packageUsage.setRemainVideoCapacity(dictPackage.getVideoCapacity());
            packageUsage.setBalance(dictPackage.getPrice());
            packageUsage.setPackageType((byte)0);
            packageUsage.setUserId(user.getId());

            //将新注册用户的对应资源写入数据库
            if(packageUsageMapper.insertSelective(packageUsage) > 0){
                UserInfoResponseBody userInfoResponseBody = new UserInfoResponseBody();
                userInfoResponseBody.setUserName(user.getUsername());
                userInfoResponseBody.setUserId(user.getId());
                response.setRetureValue(SUCCESS);
                response.setRetureMsg(MSG_SUCCESS);
                response.setRetureData(userInfoResponseBody);
                return response;
            }
        }
            response.setRetureValue(DATABASE_ERROR);
            response.setRetureMsg(MSG_DATABASE_ERROR);

            return response;


    }

    /**
     * 找回密码
     *
     * @param userInfo
     * @param httpServletRequest
     */

    @RequestMapping(value = "/user/forgetPassword", method = RequestMethod.POST)
    public Response forgetPassword(@RequestBody UserInfo userInfo, HttpServletRequest httpServletRequest) {
        Response response = new Response<UserInfoResponseBody>();
        User user = userMapper.selectByUserName(userInfo.getUserName());
        if (user == null) {
            response.setRetureValue(USER_DOES_NOT_EXSIT);
            response.setRetureMsg(MSG_USER_DOES_NOT_EXSIT);
            return response;
        }
        user.setPassword(userInfo.getPassword());
        if (userMapper.updateByPrimaryKey(user) > 0) {
            UserInfoResponseBody userInfoResponseBody = new UserInfoResponseBody();
            userInfoResponseBody.setUserId(user.getId());
            userInfoResponseBody.setUserName(user.getUsername());
            response.setRetureValue(SUCCESS);
            response.setRetureMsg(MSG_SUCCESS);
            response.setRetureData(userInfoResponseBody);
            return response;
        } else {
            response.setRetureValue(DATABASE_ERROR);
            response.setRetureMsg(MSG_DATABASE_ERROR);
            return response;
        }
    }

    /**
     * 重置密码
     *
     * @param updatePassword
     * @param httpServletRequest
     */
    @RequestMapping(value = "/user/updatePassword", method = RequestMethod.POST)
    public Response updatePassword(@RequestBody UpdatePassword updatePassword, HttpServletRequest httpServletRequest) {
        Response response = new Response<UserInfoResponseBody>();

        User user = userMapper.selectByUserName(updatePassword.getUserName());
        if (user == null) {
            response.setRetureValue(USER_DOES_NOT_EXSIT);
            response.setRetureMsg(MSG_USER_DOES_NOT_EXSIT);
            return response;
        }
            if (!user.getPassword().equals(updatePassword.getPassword())) {
                response.setRetureValue(PASSWORD_DISACCORD);
                response.setRetureMsg(MSG_PASSWORD_DISACCORD);
                return response;
            } else {
                user.setPassword(updatePassword.getNewPassword());
                if (userMapper.updateByPrimaryKey(user) > 0) {
                    UserInfoResponseBody userInfoResponseBody = new UserInfoResponseBody();
                    userInfoResponseBody.setUserName(user.getUsername());
                    response.setRetureValue(SUCCESS);
                    response.setRetureMsg(MSG_SUCCESS);
                    response.setRetureData(userInfoResponseBody);
                    return response;
                } else {
                    response.setRetureValue(DATABASE_ERROR);
                    response.setRetureMsg(MSG_DATABASE_ERROR);
                    return response;
                }
            }
        }

    /**
     * 获取用户详细信息
     * @param userId
     * @return user
     */
    @RequestMapping(value = "/1.0/user/{userId}", method = RequestMethod.GET)
    public Response getUserDetail(@PathVariable String userId){
        Response response=new Response();
        User user = userMapper.selectByPrimaryKey(userId);

        if (user == null) {
            response.setRetureValue(USER_DOES_NOT_EXSIT);
            response.setRetureMsg(MSG_USER_DOES_NOT_EXSIT);
            return response;
        }

        //返回部分前端需要的信息
        User usermoreinfo = new User();

        usermoreinfo.setUsername(user.getUsername());
        usermoreinfo.setHeadPicId(user.getHeadPicId());
        usermoreinfo.setAccountType(user.getAccountType());
        usermoreinfo.setVipLevel(user.getVipLevel());
        usermoreinfo.setPhone(user.getPhone());
        usermoreinfo.seteMail(user.geteMail());
        usermoreinfo.setBirthday(user.getBirthday());
        usermoreinfo.setGender(user.getGender());
        usermoreinfo.setEmployer(user.getEmployer());
        usermoreinfo.setDepartment(user.getDepartment());
        usermoreinfo.setCareer(user.getCareer());
        usermoreinfo.setIntroduction(user.getIntroduction());
        usermoreinfo.setNickName(user.getNickName());
        usermoreinfo.setTag(user.getTag());






        response.setRetureValue(SUCCESS);
        response.setRetureMsg(MSG_SUCCESS);
        response.setRetureData(usermoreinfo);
        return response;


    }

    /**
     * 第三方用户登陆
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/1.0/threeparty/xiandian")
    public Response login(HttpServletRequest request) {
        System.out.println("++++++++++++++++++++++++第三方登陆+++++++++++++++++++++++++");

        Response response = new Response();
        String uid = request.getRemoteUser();
        Principal principal = request.getUserPrincipal();
        String containerId = "";

        if (principal != null && principal instanceof AttributePrincipal) {
            AttributePrincipal aPrincipal = (AttributePrincipal) principal;
            //获取用户信息中公开的Attributes部分
            Map<String, Object> map = aPrincipal.getAttributes();
            // 获取姓名,可以根据属性名称获取其他属性
            containerId = (String) map.get("containerId");
        }
        //查询数据库
        User user = userMapper.selectByUserName(uid);

        if (user != null) {
            response.setRetureValue(SUCCESS);
            response.setRetureMsg(MSG_SUCCESS);
            response.setRetureData(user.getUsername());
        } else {
            System.out.println(containerId.substring(containerId.indexOf("ou") + 3
                    , containerId.lastIndexOf("ou") - 1));
            //记录进来的账户时那种类型
            String type = containerId.substring(containerId.indexOf("ou") + 3
                    , containerId.lastIndexOf("ou") - 1);


            //获取token
            String gettokenurl = "http://222.25.189.3:3003/open_api/authentication/" +
                    "get_access_token?key=2018041638708527" +
                    "&secret=7d95a744f77351a2c5b1cf7fc4bd5e46f1d98aae";

            responseEntity = restTemplate.getForEntity(gettokenurl, String.class);

            System.out.println("token " + responseEntity.getBody());
            String token = responseEntity.getBody().substring(
                    responseEntity.getBody().indexOf("access_token") + 15,
                    responseEntity.getBody().indexOf("expires_in") - 3);
            System.out.println("token " + token);

            String url = "";
            if (type.equals("onteacher")) {
                //教职工
                url = "http://222.25.189.3:3003/open_api/customization/" +
                        "tydbtjzgjbxx/list?" +
                        "ZGH=" + uid +
                        "&access_token=" + token;
            } else if (type.equals("onUndergraduate")) {
                //本科生登陆信息
                url = "http://222.25.189.3:3003/open_api/customization/" +
                        "tydbtbksjbxx/list?" +
                        "XH=" + uid +
                        "&access_token=" + token;
            } else {
                //研究生获取登陆用户相关信息
                url = "http://222.25.189.3:3003/open_api/customization/" +
                        "tydbtyjs/list?" +
                        "XH=" + uid +
                        "&access_token=" + token;

            }

            //调用相关接口获取数据
            System.out.println("url " + url);
            responseEntity = restTemplate.getForEntity(url, String.class);
            //剪切字符串
            System.out.println("responseEntity.getBody(): " + responseEntity.getBody());
            System.out.println("json " + responseEntity.getBody().toString().
                    substring(responseEntity.getBody().toString().indexOf("data")+7,
                            responseEntity.getBody().toString().lastIndexOf("}")-2));
            String json = responseEntity.getBody().toString().
                    substring(responseEntity.getBody().toString().indexOf("data")+7,
                            responseEntity.getBody().toString().lastIndexOf("}")-2);

            if (responseEntity.getBody().contains("1000")) {
                if (type.equals("onteacher")) {
                    //教职工资料
                    Onteacher onteacher = JSON.parseObject(json,Onteacher.class);
                    System.out.println("onteacher: " + onteacher.toString());

                    //存放数据库
                    user = new User();
                    user.setUsername(onteacher.getZGH());
                    if (onteacher.getXBDM().equals("男")) {
                        user.setGender(0);
                    } else {
                        user.setGender(1);
                    }
                    user.setNickName(onteacher.getXM());
                    user.setEmployer("西安电子科技大学");
                    user.setDepartment(onteacher.getSZDWDM());
                    user.setCareer("教职工");
                    user.setRegisterType(1);
                    user.setZzmm(onteacher.getZZMMDM());
                    user.setProfession(onteacher.getYJFX());
                    user.setJobTitle(onteacher.getZYJSGWLBDJDM());

                    int i = userMapper.insert(user);
                    if(i != 1){
                        response.setRetureValue(DATABASE_ERROR);
                        response.setRetureMsg(MSG_DATABASE_ERROR);
                        return response;
                    }
                    response.setRetureValue(SUCCESS);
                    response.setRetureMsg(MSG_SUCCESS);
                    response.setRetureData(onteacher.getZGH());
                    return response;

                } else if (type.equals("onUndergraduate")) {
                    //存放本科生数据
                    OnUndergraduate onUndergraduate = JSON.parseObject(json,OnUndergraduate.class);
                    System.out.println("onUndergraduate: " + onUndergraduate.toString());

                    //存放数据库
                    user = new User();
                    user.setUsername(onUndergraduate.getXH());
                    if (onUndergraduate.getXB().equals("男")) {
                        user.setGender(0);
                    } else {
                        user.setGender(1);
                    }
                    user.setNickName(onUndergraduate.getXM());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        user.setBirthday(sdf.parse(onUndergraduate.getCSRQ()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    user.setEmployer("西安电子科技大学");
                    user.setDepartment(onUndergraduate.getXSM());
                    user.setCareer("本科生");
                    user.setRegisterType(1);
                    user.setZzmm(onUndergraduate.getZZMMMC());
                    user.setEntryTime(onUndergraduate.getRXNY());
                    user.setProfession(onUndergraduate.getZYM());
                    user.setfGroup(onUndergraduate.getBM());
                    int i = userMapper.insert(user);
                    if(i != 1){
                        response.setRetureValue(DATABASE_ERROR);
                        response.setRetureMsg(MSG_DATABASE_ERROR);
                        return response;
                    }
                    response.setRetureValue(SUCCESS);
                    response.setRetureMsg(MSG_SUCCESS);
                    response.setRetureData(onUndergraduate.getXH());
                    return response;

                } else {
                    //存放研究生数据
                    Yjs yjs = JSON.parseObject(json,Yjs.class);
                    System.out.println("yjs: " + yjs.toString());

                    //存放数据库
                    user = new User();
                    user.setUsername(yjs.getXH());
                    if (yjs.getXBDM().equals("男")) {
                        user.setGender(0);
                    } else {
                        user.setGender(1);
                    }
                    user.setNickName(yjs.getXM());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        user.setBirthday(sdf.parse(yjs.getCSRQ()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    user.setEmployer("西安电子科技大学");
                    user.setDepartment(yjs.getYXDM());
                    user.setCareer("研究生");
                    user.setRegisterType(1);
                    user.setZzmm(yjs.getZZMMDM());
                    user.setEntryTime(yjs.getRXNY());
                    user.setProfession(yjs.getRXZYDM());
                    if(yjs.getSFZX().equals("是")){
                        user.setIsInService(0);
                    }else {
                        user.setIsInService(1);
                    }

                    int i = userMapper.insert(user);
                    if(i != 1){
                        response.setRetureValue(DATABASE_ERROR);
                        response.setRetureMsg(MSG_DATABASE_ERROR);
                        return response;
                    }
                    response.setRetureValue(SUCCESS);
                    response.setRetureMsg(MSG_SUCCESS);
                    response.setRetureData(yjs.getXH());
                    return response;
                }

            }

            response.setRetureValue(XIDIAN_API_ERROR);
            response.setRetureMsg(MSG_XIDIAN_API_ERROR);
            return response;
        }

        return response;
    }
}